﻿using AutoMapper;
using MediatR;
using Sale.Api.Application.Command.Contract;
using Sale.Domain;
using Sale.ErrorCode;
using Sale.Infrastructure.Implement;
using System.Diagnostics.Contracts;

namespace Sale.Api.Application.Handler.Contract
{
    public class UpdateContractHandler : IRequestHandler<UpdateContractCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ILogger<UpdateContractHandler> logger;
        private readonly DatabaseContext db;

        public UpdateContractHandler(IMapper mapper,ILogger<UpdateContractHandler> logger,DatabaseContext db)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.db = db;
        }
        public async Task<ApiResult<int>> Handle(UpdateContractCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            var contract = db.SqlSugar.Queryable<ContractModel>().Where(x=>x.ContractId==request.ContractId).First();
            contract = mapper.Map(request, contract);
            contract.ContractState = 0;
            contract.LoginUserId = 1;
            int r= await db.SqlSugar.Updateable(contract).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "销售合同修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "销售合同修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
